import { Injectable, Inject } from '@nestjs/common';
import { Repository } from 'typeorm';
import { Mold } from '../entity/mold.entity';
import { Product } from '../entity/product.entity';
import { SysOss } from '../entity/oss.entity';

const snowflake = require('node-snowflake').Snowflake;



@Injectable()
export class IndexService {
  constructor(
    @Inject('MOLD_REPOSITORY')
    private moldRepository: Repository<Mold>,
    @Inject('PRODUCT_REPOSITORY')
    private productRepository: Repository<Product>,
    @Inject('SYS_OSS_REPOSITORY')
    private ossRepository: Repository<SysOss>,
    @Inject('OSS_CLIENT')
    private ossClient: any,
  ) {
  }

  async findAllMold(): Promise<any[]> {
    const moldList = await this.moldRepository.find({ where: { delFlag: '0'} });
    const productList = await this.productRepository.find();
    const ossList = await this.ossRepository.find();
    productList.map((product) => {
      product.imageUrl = ossList.find((oss) => oss.ossId === product.ossId)?.url
    })
    const arr:Mold[] = []
    const updateArr:Mold[] = []
    for (const mold of moldList) {
      if (mold.productImageId === '0') {
        const tmpArr = productList.filter((product) => product.moldId === mold.id && product.imageUrl)
        if(tmpArr.length === 1){
          mold.productImageId = tmpArr[0].ossId
          mold.products = tmpArr
          updateArr.push(mold)
          arr.push(mold)
        } else if (tmpArr.length > 1) {
          mold.products = tmpArr
          arr.push(mold)
        }
      }
    }
    console.log(updateArr);
    updateArr.length?await this.moldRepository.save(updateArr):null;
    return arr;
  };

  async uploadFiles(fileList: any[]): Promise<any[]> {
    const result: any[] = []
    for (const item of fileList) {
      const file = item.file;
      const moldId = item.moldId;
      const tenantId = item.tenantId;
      const uniqueId = snowflake.nextId();
      // 上传到 OSS
      const ossRes = await this.ossClient.put(
        `2025/07/15/${uniqueId}_${file.originalname}`,
        file.buffer
      );
      result.push({
          ossId:snowflake.nextId(),
        moldId,
        tenantId,
        url: ossRes.url,
        fileName: `${uniqueId}_${file.originalname}`,
          originalName: `${uniqueId}_${file.originalname}`,
          fileSuffix:'.png',
          service:'aliyun'
      });
    }
    let obj = JSON.parse(JSON.stringify(result))
    await this.ossRepository.save(result);
    let arr = obj.map(v=>{ return { productImageId:v.ossId, id:v.moldId } })
      console.log(arr)
    await this.moldRepository.save(arr)
    return obj;
  };

}
